package sk.tramtatiri;

import org.apache.wicket.markup.ComponentTag;
import org.apache.wicket.markup.html.form.TextField;
import org.apache.wicket.model.IModel;
import org.apache.wicket.model.ResourceModel;
import org.apache.wicket.validation.IValidatable;
import org.apache.wicket.validation.validator.AbstractValidator;

import com.octo.captcha.service.image.ImageCaptchaService;

/**
 * class for fill the captcha input from captcha image
 * @author huonator
 */
public abstract class CaptchaInput extends TextField<String> {
	  private static final long serialVersionUID = -8872752724348771052L;

          /**
           * constructor of class CaptchaInput represents filling captcha input from captcha image
           * @param id
           * @param model
           * @param challengeId
           */
	  public CaptchaInput(String id, IModel<String> model, final String challengeId) {
	    super(id, model);
	    setRequired(true);
	    setLabel(new ResourceModel("label_captcha"));
	    
	    add(new AbstractValidator<String>() {
	      private static final long serialVersionUID = -8028253417920932179L;

	      @Override
	      protected void onValidate(IValidatable<String> validatable) {
	        if (!getImageCaptchaService().validateResponseForID(challengeId, validatable.getValue())) {
	          onError(this, validatable);
	        }
	      }
	    });
	  }

	  @Override
	  protected void onComponentTag(final ComponentTag tag) {
	    super.onComponentTag(tag);
	    tag.put("value", "");
	  }

          /**
           * Abstract method represents getter for captcha image service
           * @return captchService
           */
	  protected abstract ImageCaptchaService getImageCaptchaService();

          /**
           * method for error for submitting 
           * @param validator
           * @param validatable
           */
	  protected abstract void onError(AbstractValidator<String> validator, IValidatable<String> validatable);
	}
